package com.xmmj.baselibrary.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText

/**
 * 带图标点击事件的EditText
 */
class WithIConEditText constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : AppCompatEditText(context, attributeSet) {
    companion object {
        const val LEFT = 0
        const val RIGHT = 1
    }

    var increaseTouchRange = 20

    private var clickListener: OnIconClickListener? = null

    // SAM 接口
    fun interface OnIconClickListener {
        fun onIconClick(direction: Int, editText: WithIConEditText)
    }

    fun setOnIconClickListener(l: OnIconClickListener) {
        clickListener = l
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {

            val rightDrawable = compoundDrawables[2]

            val leftDrawable = compoundDrawables[0]

            leftDrawable?.let {
                val rect = Rect(
                    paddingStart - increaseTouchRange,
                    paddingTop - increaseTouchRange,
                    paddingStart + it.intrinsicWidth + compoundDrawablePadding + increaseTouchRange,
                    paddingBottom + it.bounds.bottom + increaseTouchRange
                )
                if (rect.contains(event.x.toInt(), event.y.toInt())) {
                    clickListener?.onIconClick(LEFT, this)
                    return true
                }
            }

            rightDrawable?.let {
                val rect = Rect(
                    measuredWidth - paddingEnd - it.bounds.width() - increaseTouchRange,
                    it.bounds.top + paddingTop - increaseTouchRange,
                    measuredWidth - paddingEnd + increaseTouchRange,
                    it.bounds.bottom + paddingBottom + increaseTouchRange
                )
                if (rect.contains(event.x.toInt(), event.y.toInt())) {
                    clickListener?.onIconClick(RIGHT, this)
                    return true
                }
            }
        }
        return super.onTouchEvent(event)
    }
}